<!--
 * @description  :情报管理首页
 * @descriptionDetail:情报管理首页
 * @copyright    : 浙江烟草
 * @author       : dw
 * @create       : 2022-11-19 14:37:47
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="retailBack" style="z-index: 99999"></theme-navbar>
    <!-- #endif -->

    <view class="content" style="width: 100%">
      <!-- 查询条件 -->
      <view class="nolicence-search-lay" :style="{'top': isHideNav ? 0 : '44px'}">
        <view class="u-search-btn">
          <u-search shape="round" bg-color="#fff" height="60" :showAction="false" :placeholder="searchPlac" @click="gotoSearch" @focus="gotoSearch"></u-search>
          <view class="search-right-icon u-flex">
            <!-- <u-icon
              name="NFC" custom-prefix="csbi-icon" class="u-p-r-20"
              size="38" color="#2979ff" @click="onNFC"
            ></u-icon> -->
            <u-icon name="scan" size="38" @click="onScan()"></u-icon>
          </view>
        </view>
      </view>
      <!-- 地图展示 -->
      <view :style="{width: getContainerWidth(), height: getContainerHeight()}" id="container"></view>
    </view>
  </view>
</template>

<script>
import {
  AMapMixin,
} from '@/common/AMapMixin.js';
import certificateService from '@/service/certificate/certificate.service.js';
import {
  SET_MAP_LAT_LON,
} from '@/config/setting.config.js';
import USearch from '@/uview-ui/components/u-search/u-search.vue';
import UIcon from '@/uview-ui/components/u-icon/u-icon.vue';
export default {
  components: {
    UIcon,
    USearch,
  },
  mixins: [AMapMixin, ],
  data() {
    return {
      markers: [],
      currPosition: undefined,
      archiveList: [],
      northeastLatitude: '',
      northeastLongitude: '',
      southwestLatitude: '',
      southwestLongitude: '',
      cluster: undefined,
      searchPlac: '',
      judgmentId: '',
      title: '',
      longitude: '',
      latitude: '',
      orgUuid: '',
      positionPicker: undefined,
    };
  },
  onLoad(opt) {
    this.showDefaultTitle = false;
    this.judgmentId = opt.id;
    this.judgmentInit(opt);
    let self = this;
    if (this.$deviceApi.geolocation) {
      this.$deviceApi.geolocation().then((res) => {
        self.longitude = res.longitude;
        self.latitude = res.latitude;
      });
    } else {
      self.longitude = SET_MAP_LAT_LON[0];
      self.latitude = SET_MAP_LAT_LON[1];
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.$modal.showLoading('地图加载中...');
    },
    judgmentInit(opt) {
      this.updateMixinTitle(this.title);
    },
    initAmap() {
      let self = this;
      // #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
      this.$deviceApi.geolocation().then(
          (res) => {
            self.curPos = [res.longitude, res.latitude];
            self.setMapInstance([res.longitude, res.latitude]);
          },
          (err) => {
            self.curPos = SET_MAP_LAT_LON;
            self.setMapInstance(SET_MAP_LAT_LON);
          }
      );
      // #endif
      // #ifdef H5-ONLY
      this.getCurrentLocation().then(
          (res) => {
            self.curPos = [res.lng, res.lat, ];
            self.setMapInstance([res.lng, res.lat, ]);
          },
          (err) => {
            self.curPos = SET_MAP_LAT_LON;
            self.setMapInstance(SET_MAP_LAT_LON);
          }
      );
      // #endif
    },
    setMapInstance(cords) {
      if (!this.hasInited) return;
      let self = this;
      self.curCords = new AMap.LngLat(cords[0], cords[1]);
      self.amap = new AMap.Map('container', {
        center: self.curCords,
        showControlButton: true,
        zoom: 18,
      });
      // self.amap.setZooms([13, 30,]);
      self.setCurrentPointMarker();
      this.$modal.hideLoading();
      self.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType', ], function() {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        self.amap.addControl(new AMap.ToolBar());
        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        self.amap.addControl(new AMap.Scale());
        // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000, // 超过10秒后停止定位，默认：5s
          // buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(5, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
          content: '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
        });
        self.amap.addControl(geolocation);
      });
      // 地图缩放
      self.amap.on('zoomend', function() {
        self.getNearRetailer();
      });
      // 地图移动
      self.amap.on('moveend', function() {
        self.getNearRetailer();
      });
      self.getNearRetailer();
    },
    // 获取列表数据
    getNearRetailer() {
      let bounds = this.amap.getBounds();
      let params;
      let self = this;
      let information = '';
      let errInfo = '';
      let fun = '';
      switch (Number(this.judgmentId)) {
        case 0:
          params = {
            longitudeStart: bounds.southwest.lng, // 西南
            latitudeStart: bounds.southwest.lat,
            longitudeEnd: bounds.northeast.lng,
            latitudeEnd: bounds.northeast.lat,
            licStatus: ['01', '02', '10', ],
          };
          information = '正在查询周边零售户...';
          errInfo = '该区域内没查询到零售户信息！';
          fun = certificateService.listRetailInScope;
          break;
        case 1:
          params = {
            longitudeLeft: bounds.southwest.lng, // 西南
            latitudeLeft: bounds.southwest.lat,
            longitudeRight: bounds.northeast.lng,
            latitudeRight: bounds.northeast.lat,
            page: 1,
            limit: 9999,
          };
          information = '正在查询周边无证户...';
          errInfo = '该区域内没查询到无证户信息！';
          fun = certificateService.findUnlicenseList;
          break;
        case 2:
          params = {
            longitudeLeft: bounds.southwest.lng, // 西南
            latitudeLeft: bounds.southwest.lat,
            longitudeRight: bounds.northeast.lng,
            latitudeRight: bounds.northeast.lat,
            page: 1,
            limit: 9999,
          };
          information = '正在查询周边特殊区域...';
          errInfo = '该区域内没查询到特殊区域信息！';
          fun = certificateService.listAreaInScope;
          break;
        default:
          break;
      }
      if (this.amap.getZoom() < 2) {
        this.markers = [];
        if (this.cluster) {
          this.amap.remove(this.cluster);
        }
        if (this.$storage.get('showMapZoomTip') != '1') {
          this.$modal.alert(
              '地图层级收缩，不支持查询，查询数据请将地图层级扩大。',
              '提示',
              () => {
                this.$storage.set('showMapZoomTip', '1');
              },
              '不再提示'
          );
        }
        return;
      }
      this.$modal.showLoading(information);
      this.markers = [];
      fun(params)
          .then((res) => {
            this.$modal.hideLoading();
            if (res.success) {
              self.archiveList = res.data;
              if (res.data.length != 0) {
                res.data.forEach((retailer, index) => {
                  if (retailer.latitude && retailer.longitude) {
                    this.addMarker(retailer, res.data);
                  }
                });
                this.markerCluster();
              } else {
                this.$u.toast(errInfo);
              }
            } else {
              this.$modal.hideLoading();
              self.$u.toast(res.msg);
            }
          })
          .catch((error) => {
            self.$u.toast(error);
          });
    },
    // 在地图上添加点
    addMarker(retailer, retailerData) {
      let self = this;
      let img = '';
      if (this.judgmentId == 0) {
        img = 'static/certificate/retailAccount.png';
      } else if (this.judgmentId == 1) {
        img = 'static/certificate/unlicensedAccount.png';
      } else {
        img = 'static/certificate/specialAreas.png';
      }
      let markPoint = {
        title: this.judgmentId == 2 ? retailer.areaName : retailer.companyName, // 显示的零售户名称
        icon: new AMap.Icon({
          size: new AMap.Size(26, 26), // 图标尺寸
          image: img, // 大图地址
          imageSize: new AMap.Size(26, 26), //,
        }),
        label: null,
        offset: new AMap.Pixel(-15, -15),
        position: [retailer.longitude, retailer.latitude, ], // 所需要的零售户经纬度
      };
      if (retailerData.length < 30) {
        markPoint.label = {
          content: this.judgmentId == 2 ? retailer.areaName : retailer.companyName,
          offset: new AMap.Pixel(24, 1),
        };
      }
      let point = new AMap.Marker(markPoint);
      point.setMap(this.amap); // 在地图上添加点
      point.on('click', function() {
        self.showRetailer(retailer); // 点击调用详情
      });
      this.markers.push(point);
    },
    // 点聚合方法
    markerCluster() {
      let self = this;
      let count = this.markers.length;
      let renderClusterMarkers = function(context) {
        let factor = Math.pow(context.count / count, 1 / 18);
        let div = document.createElement('div');
        let Hue = 180 - factor * 180;
        let bgColor = 'hsla(' + Hue + ',100%,50%,0.7)';
        let fontColor = 'hsla(' + Hue + ',100%,20%,1)';
        let borderColor = 'hsla(' + Hue + ',100%,40%,1)';
        let shadowColor = 'hsla(' + Hue + ',100%,50%,1)';
        div.style.backgroundColor = bgColor;
        let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
        div.style.width = div.style.height = size + 'px';
        div.style.border = 'solid 1px ' + borderColor;
        div.style.borderRadius = size / 2 + 'px';
        div.style.boxShadow = '0 0 1px ' + shadowColor;
        div.innerHTML = context.count;
        div.style.lineHeight = size + 'px';
        div.style.color = fontColor;
        div.style.fontSize = '14px';
        div.style.textAlign = 'center';
        context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
        context.marker.setContent(div);
      };
      this.amap.plugin(['AMap.MarkerClusterer', ], function() {
        if (self.cluster) {
          self.cluster.setMap(null);
        }
        self.cluster = new AMap.MarkerClusterer(
            self.amap, // 地图实例
            self.markers, // 海量点组成的数组
            {
              gridSize: 80,
              renderClusterMarker: renderClusterMarkers,
            }
        );
      });
    },
    // 查看零售户详情
    showRetailer(retailer) {
      switch (Number(this.judgmentId)) {
        case 0:
          this.$u.route('pages/retailer/retailerInfo/retailerInfo', {
            retailerUuid: retailer.retailerUuid,
          });
          break;
        case 1:
          this.setRouteParam({
            retailerUuid: retailer.retailerUuid,
          });
          this.$u.route('pages/query/nolicence/detailUnlicense');
          break;
        case 2:
          this.$u.route('pages/query/specialArea/specialAreaInfo', {
            areaUuid: retailer.areaUuid,
          });
          break;

        default:
          break;
      }
    },
    toCurrent() {
      let self = this;
      this.getCurrentLocation().then(
          (res) => {
            self.curCords = new AMap.LngLat(res.lng, res.lat);
            self.curPos = [res.lng, res.lat, ];
            self.updateCurrentPointMarker();
          },
          (err) => {
            self.updateCurrentPointMarker();
          }
      );
    },
    // 确定按钮 跳转到零售户列表页面
    gotoSearch() {
      switch (Number(this.judgmentId)) {
        case 0:
          this.$u.route('pages/retailer/retailerList/retailerList');
          break;
        case 1:
          this.$u.route('pages/query/nolicence/nolicence');
          break;
        case 2:
          this.$u.route('pages/query/specialArea/specialAreaList');
          break;

        default:
          break;
      }
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight + 'px'
      // #ifdef H5-WECHAT
      p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + 'px'
      // #endif
      return p;
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + 'px';
    },
    justInitMap() {
      this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
      this.amap = new AMap.Map('container', {
        showControlButton: true,
        zoom: 18,
      });
      this.$modal.hideLoading();
    },
    /**
     * 从扫描或NFC获取的零售户信息中提取许可证号
     * 不同的地区二维码信息不同，如果无法识别，需要修改本方法，添加相关特列
     * 通用逻辑：查找到“许可证”后的第一个数字串即认为是许可证号
     */
    getLicenseCode(scanRetailerInfo) {
      let index = scanRetailerInfo.indexOf('许可证号:');
      let qCodeStr = '';
      let lic = '';
      if (index != -1) qCodeStr = scanRetailerInfo.substring(index, scanRetailerInfo.indexOf(','));
      !qCodeStr && (qCodeStr = scanRetailerInfo.substring(0, 12));
      if (!qCodeStr) {
        lic = '';
      }
      let matches = qCodeStr.match(/[0-9]+/);
      if (matches.length > 0) lic = matches[0]; // 识别成功
      if (!this.$u.test.isEmpty(lic)) {
        try {
          lic = this.$u.trim(lic);
        } catch (e) {
          console.log(e);
        }
      }
      return lic;
    },
    // 扫描按钮
    onScan() {
      this.$deviceApi.scan && this.$deviceApi.scan().then((code) => {
        let licNo = this.getLicenseCode(code);
        if (this.$u.test.isEmpty(licNo)) {
          this.$u.toast('二维码无法识别：' + code);
          return;
        }
        this.getRetailerByCode(licNo);
      }).catch((error) => {
        this.$u.toast(error);
      });
    },
    // nfc按钮
    onNFC() {
      // #ifdef H5-DINGDING
      this.$deviceApi.nfcReader && this.$deviceApi.nfcReader().then((code) => {
        if (!code) {
          this.$u.toast('无法识别');
          return;
        }
        let nfcNo = '';
        if (code['tagId']) {
          nfcNo = code['tagId'].replace(/:/g, '');
        } else {
          nfcNo = code.replace(/:/g, '');
        }
        this.getRetailerByCode(nfcNo);
      }).catch((error) => {
        this.$u.toast(error);
      })
      // #endif
      // #ifndef H5-DINGDING
      this.$u.toast('H5不支持NFC');
      // #endif
    },
    getRetailerByCode(code) {
      certificateService
          .getRetailerListByLicenseCodes({
            licNoStr: code,
          })
          .then((rt) => {
            if (rt.success && rt.data.length > 0) {
              this.gotoDetail(rt.data[0]);
            } else {
              this.$u.toast(rt.msg);
            }
          })
          .catch((error) => {
            this.$u.toast(error);
          });
    },
    // 查看零售户详情
    gotoDetail(retailer) {
      this.$u.route('pages/retailer/retailerInfo/retailerInfo', {
        retailerUuid: retailer.retailerUuid,
      });
    },
    // 返回按钮
    retailBack() {
      this.$deviceApi.nfcStop && this.$deviceApi.nfcStop();
      let self = this;
      self.backPrev({
        paramKey: 'data',
        param: {},
      });
    },
  },
};
</script>

<style scoped lang="scss">
.page {
  padding: 0;
}

@import '../../style/certificate/common.scss';

.nolicence-search-lay {
  position: fixed;
  // #ifndef H5-DINGDING
  top: 44px;
  // #endif
  // #ifdef H5-DINGDING
  top: 0px;
  // #endif
  z-index: 99;
  width: 100%;
  padding: $cm-search-padding-row 0;
}

.search-right-icon {
  display: flex;
  position: absolute;
  right: 8%;
}

uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

#container {
  width: 100%;
  height: calc(100% - 88px);
}

.u-search-title {
  background: #fff;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
}

.u-search-btn {
  height: 44px;
  line-height: 44px;
  // padding: 0 10px;
  display: flex;
  align-items: center;
  margin: 0 20rpx;

  .u-confirm-btn {
    height: 32px;
    margin-left: 10px;
  }
}

// 搜索框内容
.u-serach-info {
  background-color: #f4f4f5;
  position: fixed;
  /* #ifdef H5-DINGDING  */
  top: 0px;
  /* #endif */
  /* #ifndef H5-DINGDING  */
  top: calc(var(--status-bar-height) + 44px);
  /* #endif */
  z-index: 1;
  width: 100%;
  padding-right: 11px;
}

.u-l-item {
  margin-top: 88px;
}

.cur-loc {
  position: absolute;
  bottom: 30px;
  left: 10px;
  padding: 5px;
  background: #fff;
  width: 35px;
  height: 35px;
  box-shadow: 0px 0px 0px 1px #ddd;
}
</style>
